home *** CD-ROM | disk | FTP | other *** search
/ Tech Arsenal 1 / Tech Arsenal (Arsenal Computer).ISO / tek-04 / bipl.zip / PROCS.ZIP / POPEN.ICN < prev    next >
Text File  |  1993-01-27  |  2KB  |  83 lines

  1. ########################################################################
  2. #    
  3. #    File:     popen.icn
  4. #    
  5. #    Subject:  Procedures for pipes
  6. #    
  7. #    Author:   Ronald Florence
  8. #
  9. #    Date:     September 28, 1992
  10. #
  11. ########################################################################
  12. #
  13. #    Version:  1.0
  14. #
  15. ###########################################################################
  16. #
  17. #  Contents:
  18. #
  19. #  popen(command, mode)
  20. #    mode == "w" writes to a pipe
  21. #    mode == "r" reads from a pipe
  22. #
  23. #  pclose(pipe)
  24. #
  25. #  On systems without real pipes (ms-dos), popen and pclose imitate
  26. #  pipes; pclose must be called after popen.  The code should run
  27. #  faster on ms-dos if dir in tempfile() points to a directory on a
  28. #  virtual disk.
  29. #
  30. #  On systems with real pipes, popen & pclose open and close a pipe.
  31. ##########################################################################
  32.  
  33. global PIPE_cmd, PIPE_fname
  34.  
  35. procedure popen(cmd, mode)
  36.   local tfn, p
  37.  
  38.   initial ("pipes" == &features) | {
  39.     PIPE_cmd := table()
  40.     PIPE_fname := table()
  41.   }
  42.   (type(PIPE_fname) ~== "table") & return open(cmd, mode || "p")
  43.   tfn := tempfile("pipe.")
  44.   upto('r', mode) & system(cmd || " > " || tfn)
  45.   p := open(tfn, mode)
  46.   PIPE_fname[p] := tfn
  47.   upto('w', mode) & PIPE_cmd[p] := cmd
  48.   return p
  49. end
  50.  
  51.  
  52. procedure pclose(pipe)
  53.   local status
  54.  
  55.   (type(PIPE_fname) ~== "table") & return close(pipe)
  56.   if \PIPE_cmd[pipe] then {
  57.     close(pipe) 
  58.     PIPE_cmd[pipe] ||:= " < " || PIPE_fname[pipe]
  59.     status := system(PIPE_cmd[pipe])
  60.   }
  61.   else status := close(pipe)
  62.   remove(PIPE_fname[pipe])
  63.   PIPE_cmd[pipe] := PIPE_fname[pipe] := &null
  64.   return status
  65. end
  66.  
  67.     # Richard Goerwitz's ever-useful generator.
  68.  
  69. procedure tempfile(template)
  70.   local temp_name
  71.   static dir
  72.  
  73.   initial {
  74.     if "UNIX" == &features then dir := "/tmp/"
  75.     else dir := ""
  76.   }
  77.   every temp_name := dir || template || right(1 to 999,3,"0") do {
  78.     close(open(temp_name)) & next
  79.     suspend \temp_name
  80.   }
  81. end
  82.